<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>图片加水印工具</title>
    <link rel="stylesheet" type="text/css" href="css/reset.min.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            text-align: center;
        }

        .header {
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 20px;
        }

        h1 {
            font-size: 24px;
            margin: 0 auto 0 auto;
        }

        .toolbox-link {
            position: absolute;
            top: 20px;
            right: 20px;
        }

        label {
            font-size: 16px;
            margin-right: 5px;
        }

        input[type="number"] {
            width: 60px;
            padding: 5px;
            margin-right: 10px;
            border-radius: 3px;
            border: 1px solid #ccc;
        }

        button {
            padding: 8px 16px;
            font-size: 16px;
            border: none;
            border-radius: 3px;
            background-color: #007bff;
            color: #fff;
            cursor: pointer;
        }

        button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }

        .image-container {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            margin-top: 20px;
        }

        .image-container img {
            max-height: 300px;
            margin: 5px;
            object-fit: cover;
            transition: transform 0.3s ease;
        }

        .image-container img:hover {
            transform: scale(2);
        }

        .img-box {
            width: 90%;
            min-width: 1000px;
            border: 1px solid #ccc;
            border-radius: 10px;
            margin: 20px auto;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            background-color: #fff;
            color: gray;
            font-weight: bolder;
            font-size: 18px;
        }
    </style>
</head>

<body>
    <div class="header">
        <h1>图片加水印工具</h1>
        <a href="/" class="toolbox-link">&lt; 返回工具箱</a>
    </div>
    <div>
        <label for="pngWatermark">水印图片：</label>
        <button onclick="openFileSelector('pngWatermark')" id="pngButton">选择PNG格式水印图片</button>
        <div id="watermarkLayoutContainer" style="display: inline-block; margin-left: 10px;">
            <input type="radio" id="stretch" name="watermarkLayout" value="stretch" checked>
            <label for="stretch">拉伸</label>
            <input type="radio" id="tile" name="watermarkLayout" value="tile">
            <label for="tile">平铺</label>
            <input type="radio" id="center" name="watermarkLayout" value="center">
            <label for="tile">居中</label>
            <input type="radio" id="tilt" name="watermarkLayout" value="tilt">
            <label for="tile">倾斜</label>
        </div>
    </div>
    <div style="margin-top: 10px;">
        <label for="jpgImages">需要添加水印的图片：</label>
        <button onclick="openFileSelector('jpgImages')" id="jpgButton">选择JPG格式图片</button>
    </div>
    <div style="margin-top: 10px;">
        <button onclick="addWatermark()" id="addWatermarkButton" disabled>加水印</button>
    </div>
    <div class="img-box">
        <div>水印图片</div>
        <div class="image-container" id="watermarkContainer"></div>
    </div>
    <div class="img-box">
        <div>需要添加水印的图片</div>
        <div class="image-container" id="imageContainer"></div>
    </div>
    <div class="img-box">
        <div>加水印后的图片</div>
        <div class="image-container" id="resultContainer"></div>
    </div>
    <button onclick="downloadResultImages()" id="downloadResultImages" disabled>下载加水印后的图片</button>

    <script>
        var selectedWatermark;
        var selectedImages;
        var watermarkLayout;

        function openFileSelector(type) {

            var input = document.createElement('input');
            input.type = 'file';
            input.accept = type === 'jpgImages' ? 'image/jpeg' : 'image/png';
            input.multiple = type === 'jpgImages';
            input.addEventListener('change', function (event) {
                var files = event.target.files;
                var containerId = type === 'jpgImages' ? 'imageContainer' : 'watermarkContainer';
                var imageContainer = document.getElementById(containerId);
                imageContainer.innerHTML = '';
                for (var i = 0; i < files.length; i++) {
                    var file = files[i];
                    var img = document.createElement('img');
                    img.src = URL.createObjectURL(file); // 使用URL.createObjectURL创建临时URL
                    img.classList.add('uploaded-image');
                    imageContainer.appendChild(img);
                }
                if (type === 'jpgImages') {
                    selectedImages = files;
                    checkAndEnableAddWatermarkButton();
                } else {
                    selectedWatermark = files[0];
                    displayWatermark();
                    checkAndEnableAddWatermarkButton();
                }
            });
            input.click();

        }

        function displayWatermark() {
            var watermarkContainer = document.getElementById('watermarkContainer');
            watermarkContainer.innerHTML = '';

            if (selectedWatermark) {
                var img = document.createElement('img');
                img.src = URL.createObjectURL(selectedWatermark);
                img.classList.add('watermark-image');
                watermarkContainer.appendChild(img);
            }
        }

        function checkAndEnableAddWatermarkButton() {
            var addWatermarkButton = document.getElementById('addWatermarkButton');
            if (selectedWatermark && selectedImages) {
                addWatermarkButton.disabled = false;
            } else {
                addWatermarkButton.disabled = true;
            }
        }

        function addWatermark() {
            fetch('/clear-image-cache')
                .then(function (response) {
                    return response.text();
                })
                .then(function (message) {
                    console.log(message);
                    var formData = new FormData();
                    for (var i = 0; i < selectedImages.length; i++) {
                        var file = selectedImages[i];
                        var encodedFileName = encodeURIComponent(file.name);
                        formData.append('images', file, encodedFileName);
                    }

                    formData.append('watermark', selectedWatermark);
                    formData.append('watermark-type', 'image');

                    var selectedLayout = document.querySelector('input[name="watermarkLayout"]:checked');
                    watermarkLayout = selectedLayout.value;
                    formData.append('watermark-layout', watermarkLayout);

                    var randomParam = Date.now();
                    var url = '/watermark-add?' + randomParam;
                    fetch(url, {
                        method: 'POST',
                        body: formData,
                    })
                        .then(function (response) {
                            return response.json();
                        })
                        .then(function (result) {
                            console.log(result);
                            displayProcessedImages(result.images);
                        })
                        .catch(function (error) {
                            console.error('Image upload error:', error);
                        });
                })
                .catch(function (error) {
                    console.error('Clear image cache error:', error);
                });
        }

        async function displayProcessedImages(images) {
            var resultContainer = document.getElementById('resultContainer');
            resultContainer.innerHTML = '';

            try {
                var promises = images.map(function (imageUrl) {
                    return new Promise(function (resolve, reject) {
                        console.log(imageUrl);
                        var img = document.createElement('img');
                        img.onload = function () {
                            img.classList.add('processed-image');
                            resultContainer.appendChild(img);
                            resolve();
                        };
                        img.onerror = function () {
                            reject(new Error('Failed to load image: ' + imageUrl));
                        };
                        img.src = addRandomParam(imageUrl);
                    });
                });

                await Promise.all(promises);
                var downloadButton = document.getElementById("downloadResultImages");
                downloadButton.disabled = false;
            } catch (error) {
                console.error('Error:', error);
            }
        }

        function addRandomParam(url) {
            var randomParam = Date.now();
            return url + '?' + randomParam;
        }

        function downloadResultImages() {
            fetch('/download-result-images')
                .then(function (response) {
                    return response.blob();
                })
                .then(function (blob) {
                    var timestamp = Date.now();
                    var link = document.createElement('a');
                    link.href = URL.createObjectURL(blob);
                    link.download = '加水印_' + timestamp + '.zip';
                    link.click();
                    URL.revokeObjectURL(link.href);
                })
                .catch(function (error) {
                    console.error('Download images error:', error);
                });
        }
    </script>
</body>

</html>